import React from 'react'
import leftSrc from '../../../res/images/web/euro/上轮@2x.png'
import downSrc from '../../../res/images/web/euro/下拉@2x.png'
import rightSrc from '../../../res/images/web/euro/下轮@2x.png'
import planSrc from "../../../res/images/web/euro/方案logo@2x.png"
import fireSrc from "../../../res/images/web/euro/火@2x.png"
import homeSrc from "../../../res/images/web/euro/欧洲杯／主队-缺省@2x.png"
import awaySrc from "../../../res/images/web/euro/欧洲杯／客队-缺省@2x.png"
import {withRouter} from 'react-router-dom'

import {Modal, PickerView, Toast} from "antd-mobile";
import {getEuroGameReq, getEuroGameVisitorReq, getEuroQuestionnaireSubmitStatusReq} from "../../../apis/goApis";
import LocalStorageService from "../../../utils/LocalStorageService";
import {pushWithSearch, searchParams} from "../../mall/mall";
import {getDom, log} from "../../../utils/commonfunc";
import moment from "moment";
import videoSrc from "../../../res/images/web/euro/video@2x.png"
import {addLinkAndClick} from "../../GradePlayer/GradePlayer";
import EuroGameCard from "./euro-game-card";
import questionSrc from "../../../res/images/web/euro/方案有奖备份@2x.png"
import fingerSrc from "../../../res/images/web/euro/动态手指@2x.png"


class Schedule extends React.Component {
    constructor(props) {
        super(props)
        this.searchParams = searchParams()
        this.uid = this.searchParams.webview === 'true' ? this.searchParams.uid : LocalStorageService.get('userid')
        this.state = {
            now: '小组赛 - 第1轮',
            select: ['小组赛 - 第1轮'],
            selectData: [
                {
                    label: '小组赛 - 第1轮',
                    value: '小组赛 - 第1轮',
                },
                {
                    label: '小组赛 - 第2轮',
                    value: '小组赛 - 第2轮',
                },
                {
                    label: '小组赛 - 第3轮',
                    value: '小组赛 - 第3轮',
                },
                {
                    label: '1/8决赛',
                    value: '1/8决赛',
                },
                {
                    label: '1/4决赛',
                    value: '1/4决赛',
                },

                {
                    label: '半决赛',
                    value: '半决赛',
                },
                {
                    label: '决赛',
                    value: '决赛',
                },
            ],
            games: [],
            submit: false,
            modal: {
                schedule: false,
            }
        }
    }

    componentDidMount() {
        this.getSubmitStatus()
        this.getGame()
    }

    getSubmitStatus = () => {
        if (this.uid) {
            getEuroQuestionnaireSubmitStatusReq({Uid: this.uid})
                .then(res => {
                    const data = res.data
                    if (data.ok) {
                        const submit = data.res === 1
                        this.setState({
                            submit: submit,
                        })
                    }
                })
        }
    }

    getGame = (check = true) => {
        let req
        let params = {Uid: this.uid,}
        if (this.uid) {
            req = getEuroGameReq({Uid: this.uid})
        } else {
            req = getEuroGameVisitorReq()
        }
        req
            .then(res => {
                const data = res.data
                if (res.data.ok) {
                    const gameData = data.ok
                    const planData = data.scheme

                    let games = []
                    gameData.map((game, i) => {
                        const style = game.Style
                        const plan = planData[i]
                        if (games[style - 1]) {
                            games[style - 1].push({...game, ...plan})
                        } else {
                            games[style - 1] = [{...game, ...plan}]
                        }
                    })
                    const groups = []
                    games[0].map(game => {
                        const g = game.Lun
                        if (groups[g - 1]) {
                            groups[g - 1].push(game)
                        } else {
                            groups[g - 1] = [game,]
                        }
                    })
                    games = [
                        ...groups,
                        ...games.slice(1)
                    ]
                    log(games)
                    this.setState({
                        games,
                    }, () => {
                        if (check) {
                            this.checkLatestGame()
                        }
                        setTimeout(() => this.getGame(false), 10000 )
                    })
                }

            })

    }

    checkLatestGame = () => {
        const games = this.state.games
        let currentRound = games.findIndex(round => round.some(game => game.State === 1 || (game.State >= 2 && game.State <= 7)))

        if (games.every(round => round.every(game => game.State === 8))) {
            log('全部结束')
            currentRound = games.length - 1
        }

        const round = games[currentRound]

        const index = round.findIndex(game => game.State === 1 || (game.State >= 2 && game.State <= 7))
        let prevRounds = []
        let prevRoundCount = 0
        if (currentRound > 0) {
            prevRounds = games.slice(0, currentRound)
            prevRoundCount = prevRounds.reduce((cur, acc) => cur + acc.length, 0)
        }
        const scrollGamesCount = prevRoundCount + index
        const gameCardHeight = 111 + 8
        const headerHeight = 26
        const scrollHeight = gameCardHeight * scrollGamesCount + (prevRounds.length + 1) * headerHeight + prevRounds.length * 8
        const container = getDom('.am-tabs-pane-wrap-active')
        container.scrollTop = scrollHeight
        const now = this.state.selectData[currentRound].value
        this.setState({
            now,
        })
    }

    callModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: true,
            }
        })
    }

    cancelModal = (key) => {
        this.setState({
            modal: {
                ...this.state.modal,
                [key]: false,
            }
        })
    }

    onSelectChange = (value) => {
        this.setState({
            select: value,
        })
    }

    setSelectAtIndex = (i) => {
        const sd = this.state.selectData
        if (i < 0) {
            i = 0
        } else if (i > sd.length - 1) {
            i = sd.length - 1
        }
        const s = sd[i]
        this.setState({
            select: [s.value],
            now: s.value,
        }, () => {
            addLinkAndClick('#' + this.state.now)
        })
    }

    next = () => {
        const i = this.state.selectData.findIndex(s => s.value === this.state.select[0])
        this.setSelectAtIndex(i + 1)
    }

    prev = () => {
        const i = this.state.selectData.findIndex(s => s.value === this.state.select[0])
        this.setSelectAtIndex(i - 1)
    }

    onScheduleSelect = () => {
        this.setState({
            now: this.state.select[0],
        }, () => this.cancelModal('schedule'))
    }

    goTo = (end) => {
        this.props.history.push('./' + end)
    }

    goToMyEuroPlan = () => {
        // this.goTo('my-euro-plan')
        pushWithSearch(this.props.history, './my-euro-plan')
    }

    goToQuestion = () => {
        // this.goTo('my-euro-plan')
        if (this.uid) {
            pushWithSearch(this.props.history, './euro-questionnaire')
        } else {
            Toast.info('请先登录')
        }
    }

    goToEuroPlan = (game, home = true) => {
        // log(game)
        // this.goTo('euro-plan/' + game.Id)
        // this.props.history.push('./euro-plan/' + game.Id, {home,})
        if (this.uid) {
            const status = game.State
            if (status >= 2 && status <= 7) {
                Toast.info('比赛已开始，无法支持')
            } else {
                pushWithSearch(this.props.history, './euro-plan/' + game.Id, {home,})
            }
        }
    }

    renderGames = () => {
        const games = this.state.games
        const titles = this.state.selectData
        return games.map((round, index) => {
            const text = titles[index].label
            const title = (
                <div className='euro-schedule-round' id={text}>
                    <span>{text}</span>
                </div>
            )
            const gs = <div className='euro-schedule-games-container'>
                {/*{round && round.map((game) => this.renderGame(game))}*/}
                {round && round.map((game, index) => <EuroGameCard game={game} key={index} goToEuroPlan={this.goToEuroPlan}/>)}
            </div>
            return (
                <React.Fragment key={index}>
                    {title}
                    {gs}
                </React.Fragment>
            )
        })
    }

    render() {

        const header = (
            <div className='euro-schedule-header flex-space-between-align-center'>
                <div className='flex-align-center'
                     onClick={this.prev}
                >
                    <img src={leftSrc} alt='' className='euro-schedule-header-icon'/>
                    <p className='mg-l-4px'>上一轮</p>
                </div>
                <div className='flex-align-center'
                     onClick={() => this.callModal('schedule')}
                >
                    <p>{this.state.now}</p>
                    <img src={downSrc}
                         alt=''
                         className='euro-schedule-header-icon'
                         style={{
                             marginLeft: '4px',
                         }}
                    />

                </div>
                <div className='flex-align-center'
                     onClick={this.next}
                >
                    <p className='mg-r-4px'>下一轮</p>
                    <img src={rightSrc} alt='' className='euro-schedule-header-icon'/>
                </div>


            </div>
        )

        const popup = (
            <Modal
                visible={this.state.modal.schedule}
                animationType="slide-up"
                popup
                maskClosable={false}
                onClose={() => this.cancelModal('schedule')}
                afterClose={() => {
                    addLinkAndClick('#' + this.state.select[0])
                }}
            >
                <div className='flex-space-between-align-center pd-16-px'>
                    <span onClick={() => this.cancelModal('schedule')}>
                        取消
                    </span>
                    <span
                        style={{color: '#36C8B9',}}
                        onClick={this.onScheduleSelect}
                    >
                        确定
                    </span>
                </div>
                <PickerView
                    data={this.state.selectData}
                    value={this.state.select}
                    cascade={false}
                    onChange={this.onSelectChange}
                />
            </Modal>
        )

        const planLogo = (
            <img
                alt=''
                src={planSrc}
                className='euro-schedule-plan-logo'
                onClick={this.goToMyEuroPlan}
            />
        )

        const questionLogo = (
            <div className='euro-schedule-question-logo-container' onClick={this.goToQuestion}>
                <img
                    className='euro-schedule-question-logo'
                    alt=''
                    src={questionSrc}
                />
                <img
                    className='euro-schedule-question-logo-finger'
                    src={fingerSrc}
                    alt=''
                />
            </div>
        )

        const gameTemplate = this.renderGames()

        return (
            <>
                {popup}
                <div className='euro-schedule-container' ref={el => this.container = el}>
                    {header}
                    {planLogo}
                    {!this.state.submit && questionLogo}
                    {gameTemplate}
                </div>
            </>
        )
    }
}

export default withRouter(Schedule)